package NC97_字符串出现次数的TopK问题;

import java.util.*;


public class Solution {
    /**
     * return topK string
     * @param strings string字符串一维数组 strings
     * @param k int整型 the k
     * @return string字符串二维数组
     */
    public String[][] topKstrings (String[] strings, int k) {
        // write code here
        if (k == 0){
            return new String[][]{};
        }
        String[][] res = new String[k][2];
        TreeMap<String, Integer> map = new TreeMap<>();
        // 统计各个字符串出现的次数
        for (String s : strings) {
            if (map.containsKey(s)) {
                map.put(s, map.get(s) + 1);
            } else {
                map.put(s, 1);
            }
        }

        ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        // 先按照出现的次数排序，相同则按照字符串ASCII码表排序
        list.sort((o1, o2) ->
                (o1.getValue().compareTo(o2.getValue()) == 0
                        ? o1.getKey().compareTo(o2.getKey())
                        : o2.getValue().compareTo(o1.getValue()))
        );
        // 返回topK
        for (int i = 0; i < k; i++){
            res[i][0] = list.get(i).getKey();
            res[i][1] = String.valueOf(list.get(i).getValue());
        }
        return res;
    }
}